import { defineStore } from 'pinia';
import { WindLayer } from 'cesium-wind-layer';
import * as Cesium from 'cesium';
import { useScaleStore } from "@/stores/scaleStore";


export const useCurrentStore = defineStore('current', {
  state: () => ({
    viewer: null, // Cesium Viewer 实例
    windData: null, // 风场数据
    currentLayer: null, // WindLayer 实例
    isVisible: false, // 显隐状态
    handler: null, // 事件处理器
    interpolatedColors:["#2ad587", "#55a666", "#807644", "#807644", "#ab4622", "#d61600"], // 颜色映射
  }),
  actions: {
    // 设置 Viewer
    setViewer(viewer) {
      this.viewer = viewer;
    },

    // 设置风场数据
    setWindData(windData) {
      this.windData = windData;
    },
    setinterpolatedColors(interpolatedColors) {
      this.interpolatedColors = interpolatedColors;
    },

    // 加载风场数据
    loadCurrent() {
      if (this.currentLayer) {
        this.currentLayer.remove(); // 移除旧的风场图层
      }

      // 处理风场数据
      const processedData = this.processWindData(this.windData);

      // 定义颜色插值
      // const interpolatedColors = ["#8ee80e", "#96ce10", "#9eb70e", "#a6a00c", "#ae890a", "#b67208", "#be5b06", "#c64404", "#ce2d02", "#d61600"];
      // const interpolatedColors = ["#2ad587", "#55a666", "#807644", "#807644", "#ab4622", "#d61600"];
      // 创建 WindLayer
      this.currentLayer = new WindLayer(this.viewer, processedData, {
        particlesTextureSize: 200, // 粒子系统的纹理大小
        particleHeight: 100, // 粒子距地面高度
        lineWidth: { min: 1, max: 1.8 }, // 粒子轨迹宽度范围
        lineLength: { min: 80, max: 100 }, // 粒子轨迹长度范围
        speedFactor: 2.0, // 速度倍数
        dropRate: 0.003, // 粒子消失率
        dropRateBump: 0.01, // 慢速粒子的额外消失率
        colors: this.interpolatedColors, // 粒子颜色
        flipY: false, // 是否翻转 Y 坐标
        dynamic: true, // 是否启用动态粒子动画
      });

      // 缩放到风场范围
      // this.currentLayer.zoomTo();

      // 添加点击事件监听器
      this.addMouseMoveHandler();
    },

    // 处理风场数据
    processWindData(data) {
      // 查找 u 和 v 参数的数据
      const uData = data.find((d) => d.header.parameterNumber === 2);
      const vData = data.find((d) => d.header.parameterNumber === 3);

      // 将 u 和 v 的数据转换为数组并处理字符串数值及 "NaN"
      const parseValue = (value) => {
        const parsed = parseFloat(value);
        return isNaN(parsed) ? 0 : parsed;
      };

      const uArray = Array.from(uData.data, parseValue);
      const vArray = Array.from(vData.data, parseValue);

      // 获取网格的宽度和高度
      const width = uData.header.nx;
      const height = uData.header.ny;

      // 获取边界信息
      const bounds = {
        west: uData.header.lo1,
        north: uData.header.la2,
        east: uData.header.lo2,
        south: uData.header.la1,
      };

      // 获取单位、名称和时间
      const unit = uData.header.parameterUnit;
      const name = 'wind_10m';
      const time = new Date(uData.header.refTime).getTime();

      // 返回处理后的对象
      return {
        bounds: bounds,
        width: width,
        height: height,
        unit: unit,
        name: name,
        time: time,
        u: {
          array: uArray,
        },
        v: {
          array: vArray,
        },
      };
    },

    // 切换显隐状态
    toggleCurrentVisibility() {
      this.isVisible = !this.isVisible;
      if (this.isVisible) {
        this.loadCurrent(); // 显示风场
      } else {
        if (this.currentLayer) {
          this.currentLayer.remove(); // 隐藏风场
          this.currentLayer = null;
        }
        if (this.handler) {
          this.handler.destroy(); // 销毁事件处理器
          this.handler = null;
        }
      }
    },

    // 添加点击事件监听器
    // 添加鼠标移动事件监听器
addMouseMoveHandler() {
    if (!this.viewer || !this.currentLayer) return;
  
    // 销毁旧的事件处理器
    if (this.handler) {
      this.handler.destroy();
    }
  
    // 创建新的事件处理器
    this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
    this.handler.setInputAction((movement) => {
      const scaleStore = useScaleStore();
                const scale = scaleStore.currentScale || 1;
          
                // 反向计算：鼠标坐标除以缩放比例
                const adjustedX = movement.endPosition.x / scale;
                const adjustedY = movement.endPosition.y / scale;
                const adjustedPosition = new Cesium.Cartesian2(adjustedX, adjustedY);
      const ray = this.viewer.camera.getPickRay(adjustedPosition);
      if (!ray) return;
  
      // 获取鼠标位置的经纬度
      const cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene);
      if (!cartesian) return;
  
      const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
      const lon = Cesium.Math.toDegrees(cartographic.longitude);
      const lat = Cesium.Math.toDegrees(cartographic.latitude);
  
      // 获取海流信息
      const windData = this.getDataAtLonLat(lon, lat);
      if (windData) {
        const { interpolated, original } = windData;
  
        // 触发事件，传递海流信息
        this.emitWindData({
          lon: lon.toFixed(4),
          lat: lat.toFixed(4),
          interpolated: {
            speed: interpolated.speed.toFixed(2),
            u: interpolated.u.toFixed(2),
            v: interpolated.v.toFixed(2),
          },
          original: {
            speed: original.speed.toFixed(2),
            u: original.u.toFixed(2),
            v: original.v.toFixed(2),
          },
        });
      } else {
        // 如果没有数据，传递空值
        this.emitWindData(null);
      }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  },
  
  // 触发事件，传递海流信息
  emitWindData(data) {
    const event = new CustomEvent('wind-data', { detail: data });
    window.dispatchEvent(event);
  },
    // 获取指定经纬度的风场数据
    getDataAtLonLat(lon, lat) {
      if (!this.currentLayer) return null;
      return this.currentLayer.getDataAtLonLat(lon, lat);
    },
  },
});